package com.fen.asunder;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.qq.e.ads.banner.ADSize;
import com.qq.e.ads.banner.AbstractBannerADListener;
import com.qq.e.ads.banner.BannerView;
import com.qq.e.ads.interstitial.AbstractInterstitialADListener;
import com.qq.e.ads.interstitial.InterstitialAD;
import com.qq.e.comm.util.AdError;

import java.util.Random;

public class MainActivity extends AppCompatActivity {
    private static Boolean isShown = false;
    private static boolean isDestroy = false;
    private static WindowManager mWindowManager;
    private static BannerView banner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取悬浮窗权限
        FloatWindowManager.getInstance().applyOrShowFloatWindow(this);
        RelativeLayout l = (RelativeLayout) findViewById(R.id.adcontent);
        // 创建Banner广告AdView对象
        // appId : 在 http://e.qq.com/dev/ 能看到的app唯一字符串
        // posId : 在 http://e.qq.com/dev/ 生成的数字串，并非 appid 或者 appkey
        BannerView banner = new BannerView(this, ADSize.BANNER, "1105400838", getBannerId());
        //设置广告轮播时间，为0或30~120之间的数字，单位为s,0标识不自动轮播
        banner.setRefresh(30);
        banner.setADListener(new AbstractBannerADListener() {

            @Override
            public void onNoAD(AdError error) {
                Log.i("AD_DEMO", "BannerNoAD，eCode=" + error.getErrorCode());
            }

            @Override
            public void onADReceiv() {
                Log.i("AD_DEMO", "ONBannerReceive");
            }

            @Override
            public void onADClicked() {
                super.onADClicked();
                Toast.makeText(getApplicationContext(), "广告被点击", Toast.LENGTH_SHORT).show();
            }
        });
        /* 发起广告请求，收到广告数据后会展示数据   */
        banner.loadAD();
        l.addView(banner);
        findViewById(R.id.showInsertAd).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                insertAd();
            }
        });
        showInWindow();
    }

    private void insertAd() {
        final InterstitialAD iad = new InterstitialAD(this, "1105400838", "4090835584142557");
        iad.setADListener(new AbstractInterstitialADListener() {
            @Override
            public void onNoAD(AdError error) {
                Log.i("AD_DEMO", String.format("LoadInterstitialAd Fail, error code: %d, error msg: %s", error.getErrorCode(), error.getErrorMsg()));
            }

            @Override
            public void onADReceive() {
                /*
                 * 展示插屏广告，仅在回调接口的adreceive事件发生后调用才有效。
                 */
                Log.i("AD_DEMO", "接收到广告");
                iad.show();
            }
        });
        //请求插屏广告，每次重新请求都可以调用此方法。
        iad.loadAD();
        iad.showAsPopupWindow();
    }

    public String getBannerId() {
        String id[] = {"5000117455290979", "2090630524144698"};
        return id[new Random().nextInt(2)];
    }

    private void showInWindow() {
        new Thread(new Runnable() {

            private BannerView banner;
            private AlertDialog.Builder builder;
            private AlertDialog dialog;

            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000 * 60 * 5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            test();
                        }

                    });
                    try {
                        Thread.sleep(1000 * 30);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                hidePopupWindow();
                            }
                        });
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
    }

    private void test() {
        if (isShown) {
            return;
        }
        isShown = true;
        mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        // 类型
        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        // WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
        int flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        // | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        // 如果设置了WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE，弹出的View收不到Back键的事件
        params.flags = flags;
        // 不设置这个弹出框的透明遮罩显示为黑色
        params.format = PixelFormat.TRANSLUCENT;
        // FLAG_NOT_TOUCH_MODAL不阻塞事件传递到后面的窗口
        // 设置 FLAG_NOT_FOCUSABLE 悬浮窗口较小时，后面的应用图标由不可长按变为可长按
        // 不设置这个flag的话，home页的划屏会有问题
        banner = new BannerView(this, ADSize.BANNER, "1105400838", getBannerId());
        banner.setRefresh(30);
        banner.setADListener(new AbstractBannerADListener() {

            @Override
            public void onNoAD(AdError error) {
                Log.i("AD_DEMO", "BannerNoAD，eCode=" + error.getErrorCode());
            }

            @Override
            public void onADReceiv() {
                Log.i("AD_DEMO", "ONBannerReceive");
            }

            @Override
            public void onADClicked() {
                super.onADClicked();
                Toast.makeText(getApplicationContext(), "广告被点击", Toast.LENGTH_SHORT).show();
                hidePopupWindow();
            }
        });
        banner.loadAD();
        ViewGroup.LayoutParams layoutParams = banner.getLayoutParams();
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.BOTTOM;
        banner.setId(R.id.wrap);
        mWindowManager.addView(banner, params);
    }

    public static void hidePopupWindow() {
        isDestroy = true;
        if (isShown && null != banner) {
            try {
                mWindowManager.removeView(banner);
            } catch (Exception e) {
                e.printStackTrace();
            }
            isShown = false;
        }
        isShown = false;
    }

}
